package com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush;

import android.app.Notification;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.yuntoyun.fwcore.R;
import com.yuntoyun.fwcore.config.FwAppConfig;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.MultiActionsNotificationBuilder;

import static android.content.Context.MODE_PRIVATE;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_ADD;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_CHECK;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_CLEAN;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_DELETE;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_GET;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.ACTION_SET;
import static com.yuntoyun.codeavatar.app.fwcore.plug.jiguang.jpush.TagAliasOperatorHelper.sequence;

public class PlugJpush {

    private static PlugJpush init = null;

    private static final Object mLock = new Object();

    public static PlugJpush builder() {
        if (null == init) {
            synchronized (mLock) {
                if (null == init) {
                    init = new PlugJpush();
                }
            }
        }
        return init;
    }

    public void doInit(Context context) {
        JPushInterface.setDebugMode(FwAppConfig.PRINT_LOG_SWITCH);    // 设置开启日志,发布时请关闭日志
        // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
        JPushInterface.init(context);            // 初始化 JPush
    }

    public void doStop(Context context) {
        JPushInterface.stopPush(context);
    }

    public void doResume(Context context) {
        JPushInterface.resumePush(context);
    }

    public String getRegistrationId(Context context) {
        return JPushInterface.getRegistrationID(context);
    }

    //++++++++++++++++++++++++++++++++++++++++++++
    //===TAG/ALIAS 相关
    //++++++++++++++++++++++++++++++++++++++++++++

    /**
     * 设置手机号
     *
     * @param context
     * @param mobileNumber
     * @return
     */
    public boolean setMobileNumber(Context context, String mobileNumber, JpushActionCallback
            callback) {
        if (ExampleUtil.isValidMobileNumber(mobileNumber)) {
            sequence++;
            TagAliasOperatorHelper.getInstance().handleAction(context, sequence,
                    mobileNumber, callback);
            return true;
        }
        return false;
    }

    /**
     * 添加标签
     *
     * @param context
     * @param tagstr  多个标签用英式逗号分隔
     * @return
     */
    public boolean addTag(Context context, String tagstr) {
        return this.handleAction(context, ACTION_ADD, false, null, tagstr, true, null);
    }

    public boolean setTag(Context context, String tagstr) {
        return this.handleAction(context, ACTION_SET, false, null, tagstr, true, null);
    }

    public boolean deleteTag(Context context, String tagstr) {
        return this.handleAction(context, ACTION_DELETE, false, null, tagstr, true, null);
    }

    public boolean getAllTag(Context context, JpushActionCallback callback) {
        return this.handleAction(context, ACTION_GET, false, null, null, false, callback);
    }

    public boolean clearAllTag(Context context) {
        return this.handleAction(context, ACTION_CLEAN, false, null, null, false, null);
    }

    public boolean checkAllTag(Context context, String tagstr) {
        return this.handleAction(context, ACTION_CHECK, false, null, tagstr, true, null);
    }

    public boolean setAlias(Context context, String alias) {
        return this.handleAction(context, ACTION_SET, true, alias, null, true, null);
    }

    public boolean getAlias(Context context, JpushActionCallback callback) {
        return this.handleAction(context, ACTION_GET, true, null, null, false, callback);
    }

    public boolean deleteAlias(Context context, String alias) {
        return this.handleAction(context, ACTION_DELETE, true, alias, null, true, null);
    }


    /**
     * 处理别名或标签
     *
     * @param context
     * @param action
     * @param isAliasAction
     * @param alias
     * @param tagstr
     * @param checkValid
     * @return
     */
    private boolean handleAction(Context context, int action, boolean isAliasAction,
                                 String alias, String tagstr, boolean checkValid,
                                 JpushActionCallback callback) {
        Set<String> tags = null;

        if (checkValid) {
            //校验Tag Alias 只能是数字,英文字母和中文
            if (isAliasAction) {
                if (!ExampleUtil.isValidTagAndAlias(alias)) {
                    return false;
                }
            } else {
                if (!TextUtils.isEmpty(tagstr)) {
                    // ","隔开的多个 转换成 Set
                    String[] sArray = tagstr.split(",");

                    tags = new LinkedHashSet<String>();
                    for (String tag : sArray) {
                        if (!ExampleUtil.isValidTagAndAlias(tag)) {
                            return false;
                        }
                        tags.add(tag);
                    }
                } else {
                    return false;
                }
            }
        }

        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper
                .TagAliasBean();
        tagAliasBean.action = action;
        sequence++;
        if (isAliasAction) {
            tagAliasBean.alias = alias;
        } else {
            tagAliasBean.tags = tags;
        }
        tagAliasBean.isAliasAction = isAliasAction;
        TagAliasOperatorHelper.getInstance().handleAction(context, sequence, tagAliasBean,
                callback);
        return true;
    }


    //++++++++++++++++++++++++++++++++++++++++++++
    //===设置接收Push时间
    //++++++++++++++++++++++++++++++++++++++++++++

    /**
     * 获取时间数据模型
     *
     * @param context
     * @return
     */
    public JpushTimeModel getPushTimeModel(Context context) {
        SharedPreferences mSettings = context.getSharedPreferences(ExampleUtil.PREFS_NAME,
                MODE_PRIVATE);
        JpushTimeModel model = new JpushTimeModel();
        model.setStartime(mSettings.getInt(ExampleUtil.PREFS_START_TIME, 0));
        model.setEndtime(mSettings.getInt(ExampleUtil.PREFS_END_TIME, 23));
        String days = mSettings.getString(ExampleUtil.PREFS_DAYS, "");
        // ","隔开的多个 转换成 Set
        String[] sArray = days.split(",");
        Set<JpushTimeWeek> weekSet = new LinkedHashSet<JpushTimeWeek>();
        int day = -1;
        for (String str : sArray) {
            day = Integer.parseInt(str);
            switch (day) {
                case 0:
                    weekSet.add(JpushTimeWeek.Sunday);
                    break;
                case 1:
                    weekSet.add(JpushTimeWeek.Monday);
                    break;
                case 2:
                    weekSet.add(JpushTimeWeek.Tuesday);
                    break;
                case 3:
                    weekSet.add(JpushTimeWeek.Wednesday);
                    break;
                case 4:
                    weekSet.add(JpushTimeWeek.Thursday);
                    break;
                case 5:
                    weekSet.add(JpushTimeWeek.Friday);
                    break;
                case 6:
                    weekSet.add(JpushTimeWeek.Saturday);
                    break;
            }
        }
        model.setWeekday(weekSet);
        return model;
    }

    /**
     * 设置允许接收通知时间
     */
    public boolean setPushTime(Context context, int startime, int endtime, Set<JpushTimeWeek>
            weekday) {

        if (startime > endtime) {
            FwToastUtil.builder().makeText("开始时间不能大于结束时间");
            return false;
        }
        StringBuffer daysSB = new StringBuffer();
        Set<Integer> days = new HashSet<Integer>();

        for (JpushTimeWeek day : weekday) {
            switch (day) {
                case Monday:
                    days.add(1);
                    daysSB.append("1,");
                    break;
                case Tuesday:
                    days.add(2);
                    daysSB.append("2,");
                    break;
                case Wednesday:
                    days.add(3);
                    daysSB.append("3,");
                    break;
                case Thursday:
                    days.add(4);
                    daysSB.append("4,");
                    break;
                case Friday:
                    days.add(5);
                    daysSB.append("5,");
                    break;
                case Saturday:
                    days.add(6);
                    daysSB.append("6,");
                    break;
                case Sunday:
                    days.add(0);
                    daysSB.append("0,");
                    break;
            }
        }

        //调用JPush api设置Push时间
        JPushInterface.setPushTime(context, days, startime, endtime);

        SharedPreferences mSettings = context.getSharedPreferences(ExampleUtil.PREFS_NAME,
                MODE_PRIVATE);
        SharedPreferences.Editor mEditor = mSettings.edit();
        mEditor.putString(ExampleUtil.PREFS_DAYS, daysSB.toString());
        mEditor.putInt(ExampleUtil.PREFS_START_TIME, startime);
        mEditor.putInt(ExampleUtil.PREFS_END_TIME, endtime);
        mEditor.commit();
        return true;
    }

    //++++++++++++++++++++++++++++++++++++++++++++
    //===定制通知栏样式
    //++++++++++++++++++++++++++++++++++++++++++++

    public void setAddActionsStyle(Context context) {
        MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder
                (context);
        builder.addJPushAction(R.drawable.fw_plug_jpush_ic_richpush_actionbar_back, "first",
                "my_extra1");
        builder.addJPushAction(R.drawable.fw_plug_jpush_ic_richpush_actionbar_back, "second",
                "my_extra2");
        builder.addJPushAction(R.drawable.fw_plug_jpush_ic_richpush_actionbar_back, "third",
                "my_extra3");
        JPushInterface.setPushNotificationBuilder(10, builder);
    }

    /**
     * 设置通知提示方式 - 基础属性
     */
    public void setStyleBasic(Context context, int resDrawId) {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(context);
        builder.statusBarDrawable = resDrawId;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;  //设置为点击后自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND;  //设置为铃声（ Notification
        // .DEFAULT_SOUND）或者震动（ Notification.DEFAULT_VIBRATE）
        JPushInterface.setPushNotificationBuilder(1, builder);
    }

    /**
     * 设置通知栏样式 - 定义通知栏Layout
     */
    public void setStyleCustom(Context context, int resLayoutId, int resDrawId) {

        if (-1 == resLayoutId) {
            resLayoutId = R.layout.fw_plug_customer_notitfication_layout;
        }

        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(context,
                resLayoutId, R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable = resDrawId;
        builder.developerArg0 = "developerArg2";
        JPushInterface.setPushNotificationBuilder(2, builder);
    }

}
